import 'package:flutter/foundation.dart';
import 'view_state_list_model.dart';

/// 基于
abstract class ViewStateRefreshListModel<T> extends ViewStateListModel {
  /// 分页第一页页码
  static const int pageNumFirst = 1;

  /// 分页条目数量
  static const int pageSize = 20;

  /// 当前页码
  int _currentPageNum = pageNumFirst;

  /// 首次加载
  iniData() async {
    setBusy(true);
    await refresh(init: true);
  }

  /// 下拉刷新
  refresh({bool init = false}) async {
    try {
      _currentPageNum = 1;
      List<T> data = await loadData(pageNum: _currentPageNum);
      if (data.isEmpty) {
        setEmpty();
      } else {
        _currentPageNum += 1;
        list = data;
        if (init) {
          //改变页面状态为非加载中
          setBusy(false);
        } else {
          notifyListeners();
        }
      }
    } catch (e, s) {
      handleCatch(e, s);
    }
  }

  /// 上拉加载更多
  Future<List<T>> loadMore() async {
    try {
      List<T> data = await loadData(pageNum: _currentPageNum);
      if (data.isEmpty) {
        setEmpty();
      } else {
        _currentPageNum += 1;
        list.addAll(data);
        notifyListeners();
      }
    } catch (e, s) {
      handleCatch(e, s);
    }
  }

  // 加载数据
  Future<List<T>> loadData({int pageNum}) async {}

  @override
  void dispose() {
    super.dispose();
  }
}
